#!/usr/bin/python
"""
Collect the cpu/mem/iowait info.
cmd: vmstat
output: debug.txt\vmstat_[ip].txt\nohup.out
Email: jiaoruodan@163.com
"""

import os
import subprocess
import time

DELAY = "5"
COUNT = "10000000"
rootdir = "/home/OTS-TEST"

TIMEFORMAT = '%Y%m%d%H%M%S'
curtime = time.strftime(TIMEFORMAT, time.localtime())
# ip = os.popen("ifconfig | grep \"inet\" | grep -v \"127.0.0.1\" | grep \"10.124.\" | awk -F \" \" '{print $2}' | awk '{print $1}'").readlines()
ip = os.popen(
    "ifconfig | grep \"inet \" | grep -v \"127.0.0.1\" | awk -F \" \" '{print $2}' | awk '{print $1}'").readlines()
# result_file = "/home/OTS-TEST/vmstat_" + ip[0].strip() + '_' + curtime + ".txt"
result_file_name = "%s/vmstat_" % (rootdir) + ip[0].strip() + ".txt"

t_mem = os.popen("free | grep Mem |awk -F ' ' '{print $2}'").readlines()
# t_mem = os.popen("cat /proc/meminfo |grep MemTotal| awk -F ':' '{print $2}'| awk -F ' ' '{print $1}'").readlines()

result_file = open(result_file_name, "w")
result_file.write("total mem: " + t_mem[0])
result_file.flush()

debug_file = open("%s/debug.txt" % (rootdir), "w")

# cmd1=["vmstat",DELAY,COUNT]
cmd1 = ["vmstat", DELAY]
# cmd1=["vmstat",DELAY,COUNT,"&"]
cmd2 = ["date", "+%Y.%m.%d %H:%M:%S"]

f1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
status = f1.stdout.readline()
debug_file.write(status)
debug_file.flush()

tmp = status.strip()
while tmp[0].isdigit() == False:
    status = "date time " + tmp + ' ' + 'shm' + '\n'
    print status
    result_file.write(status)
    result_file.flush()
    status = f1.stdout.readline()
    debug_file.write(status)
    debug_file.flush()
    tmp = status.strip()

line = status
while line:
    # add testtime
    f3 = subprocess.Popen(cmd2, stdout=subprocess.PIPE)
    testtime = f3.stdout.readline().strip()

    # add shmem
    shmem = os.popen("cat /proc/meminfo | grep Shmem | awk -F ':' '{print $2}'| awk -F ' ' '{print $1}'").readlines()[0]
    shmem = shmem.strip()

    while tmp[0].isdigit() == False:
        status = "date time " + tmp + ' ' + 'shm' + '\n'
        print status
        status = f1.stdout.readline()
        debug_file.write(status)
        debug_file.flush()
        tmp = status.strip()

    line = testtime + " " + tmp + " " + shmem + '\n'
    result_file.write(line)
    result_file.flush()
    print line

    time.sleep(int(DELAY))
    status = f1.stdout.readline()
    debug_file.write(status)
    debug_file.flush()
    line = status
    tmp = status.strip()

result_file.close()
debug_file.close()
